package cn.tedu.travelsystem.itinerary.controller;

import cn.tedu.travelsystem.base.response.JsonResult;
import cn.tedu.travelsystem.base.response.StatusCode;
import cn.tedu.travelsystem.base.utils.AccessLimitUtil;
import cn.tedu.travelsystem.itinerary.mapper.ItineraryMapper;
import cn.tedu.travelsystem.itinerary.pojo.dto.ItineraryDTO;
import cn.tedu.travelsystem.itinerary.pojo.dto.ItineraryRequestDTO;
import cn.tedu.travelsystem.itinerary.pojo.entity.Itinerary;
import cn.tedu.travelsystem.itinerary.pojo.vo.ItineraryVO;
import cn.tedu.travelsystem.itinerary.service.ItineraryService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/itineraries")
@Api(tags = "07.行程模块")
public class ItineraryController {

    @Autowired
    private ItineraryMapper itineraryMapper;
    @Autowired
    ItineraryService itineraryService;

    @Autowired
    private AccessLimitUtil accessLimitUtil; // 引入访问限制工具类

    // 添加行程信息
    @PostMapping
    @ApiOperation("添加行程信息")
    @ApiOperationSupport(order = 10)
    public JsonResult addItinerary(@Validated @RequestBody ItineraryDTO dto, HttpServletRequest request) {
        // 异常访问检测
        String ip = request.getRemoteAddr();
        String key = "limit:ip:" + ip;
        if (accessLimitUtil.isFrequent(key, 20, 60)) {
            // 发送警告信息
            log.warn("IP [{}] 频繁访问，60秒内请求超过限制", ip);
            return new JsonResult(StatusCode.REQUEST_TOO_FREQUENT);
        }

        log.debug("ItineraryDTO = " + dto);
        Itinerary itinerary = new Itinerary();
        BeanUtils.copyProperties(dto, itinerary);
        int rows = itineraryMapper.insert(itinerary);
        if (rows > 0) {
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    // 删除行程信息
    @DeleteMapping("/{itineraryId}")
    @ApiOperation("删除行程信息")
    @ApiOperationSupport(order = 20)
    public JsonResult deleteItinerary(@PathVariable Integer itineraryId, HttpServletRequest request) {
        // 异常访问检测
        String ip = request.getRemoteAddr();
        String key = "limit:ip:" + ip;
        if (accessLimitUtil.isFrequent(key, 20, 60)) {
            // 发送警告信息
            log.warn("IP [{}] 频繁访问，60秒内请求超过限制", ip);
            return new JsonResult(StatusCode.REQUEST_TOO_FREQUENT);
        }

        log.debug("itineraryId = " + itineraryId);
        int rows = itineraryMapper.deleteById(itineraryId);
        if (rows > 0) {
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    // 更新行程信息
    @PutMapping("/{itineraryId}")
    @ApiOperation("更新行程信息")
    @ApiOperationSupport(order = 30)
    public JsonResult updateItinerary(@PathVariable Integer itineraryId, @Validated @RequestBody ItineraryDTO dto, HttpServletRequest request) {
        // 异常访问检测
        String ip = request.getRemoteAddr();
        String key = "limit:ip:" + ip;
        if (accessLimitUtil.isFrequent(key, 20, 60)) {
            // 发送警告信息
            log.warn("IP [{}] 频繁访问，60秒内请求超过限制", ip);
            return new JsonResult(StatusCode.REQUEST_TOO_FREQUENT);
        }

        log.debug("itineraryId = " + itineraryId + ", ItineraryDTO = " + dto);
        Itinerary itinerary = new Itinerary();
        BeanUtils.copyProperties(dto, itinerary);
        itinerary.setItinerary_id(itineraryId);
        int rows = itineraryMapper.update(itinerary);
        if (rows > 0) {
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    // 查询单个行程信息
    @GetMapping("/{itineraryId}")
    @ApiOperation("查询单个行程信息")
    @ApiOperationSupport(order = 40)
    public JsonResult getItinerary(@PathVariable Integer itineraryId, HttpServletRequest request) {
        // 异常访问检测
        String ip = request.getRemoteAddr();
        String key = "limit:ip:" + ip;
        if (accessLimitUtil.isFrequent(key, 20, 60)) {
            // 发送警告信息
            log.warn("IP [{}] 频繁访问，60秒内请求超过限制", ip);
            return new JsonResult(StatusCode.REQUEST_TOO_FREQUENT);
        }

        log.debug("itineraryId = " + itineraryId);
        Itinerary itinerary = itineraryMapper.selectById(itineraryId);
        if (itinerary != null) {
            ItineraryVO vo = new ItineraryVO();
            BeanUtils.copyProperties(itinerary, vo);
            return JsonResult.ok(vo);
        } else {
            return new JsonResult(StatusCode.DATA_NOT_FOUND);
        }
    }

    // 查询所有行程信息
    @GetMapping
    @ApiOperation("查询所有行程信息")
    @ApiOperationSupport(order = 50)
    public JsonResult getAllItineraries(HttpServletRequest request) {
        // 异常访问检测
        String ip = request.getRemoteAddr();
        String key = "limit:ip:" + ip;
        if (accessLimitUtil.isFrequent(key, 20, 60)) {
            // 发送警告信息
            log.warn("IP [{}] 频繁访问，60秒内请求超过限制", ip);
            return new JsonResult(StatusCode.REQUEST_TOO_FREQUENT);
        }

        log.debug("查询所有行程信息");
        List<Itinerary> itineraries = itineraryMapper.selectAll();
        List<ItineraryVO> vos = new ArrayList<>();
        for (Itinerary itinerary : itineraries) {
            ItineraryVO vo = new ItineraryVO();
            BeanUtils.copyProperties(itinerary, vo);
            vos.add(vo);
        }
        return JsonResult.ok(vos);
    }

    // ItineraryController.java 新增接口
    @PostMapping("/generate")
    @ApiOperation("生成推荐行程")
    @ApiOperationSupport(order = 60)
    public JsonResult generateItinerary(@Validated @RequestBody ItineraryRequestDTO requestDTO) {
        log.debug("ItineraryRequestDTO = " + requestDTO);
        ItineraryVO generatedItinerary = itineraryService.generateItinerary(requestDTO);
        return JsonResult.ok(generatedItinerary);
    }

}